package com.findfuture.demo.controller;

import com.findfuture.common.exception.MyException;
import com.findfuture.common.util.Constants;
import com.findfuture.common.util.CookieUtil;
import com.findfuture.common.util.PasswordEncoder;
import com.findfuture.common.util.StringUtil;
import com.findfuture.demo.model.Users;
import com.findfuture.demo.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 * User: Alex
 * Date: 11-11-19
 * Time: 下午9:49
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/user")
@SessionAttributes({Constants.USER_INFO_SESSION, "token"})

public class UserController {

    @RequestMapping("/userAddAction")
    public String userAddAction(Users users, ModelMap modelMap, int relation, String token, @ModelAttribute("token") String sessionToken) {
        users.setJoinDate(new java.sql.Date(new java.util.Date().getTime()));
        if (token.equals(sessionToken))
            try {
                users.setPassword(PasswordEncoder.encode(users.getUserName(), users.getPassword()));
                usersService.addOrUpdate(users);
                if (relation != 0) {
                    //添加用户关联关系
                    usersService.addUserRelation(users.getId(), relation);
                }
                modelMap.addAttribute("success", "用户添加成功！");
            } catch (Exception e) {
                modelMap.addAttribute("error", "用户添加失败！");
            }

        return "forward:/user/userManager";
    }

    @RequestMapping("/userAdd")
    public String userAdd(ModelMap modelMap) throws Exception {
        modelMap.addAttribute("token", StringUtil.uuid());
        modelMap.addAttribute("users", usersService.getUsersList());
        modelMap.addAttribute("action", "/user/userAddAction");
        return "/user/userAdd";
    }

    @RequestMapping("/userModify/{id}")
    public String userModify(@PathVariable int id, ModelMap modelMap) throws Exception {
        modelMap.addAttribute("token", StringUtil.uuid());
        modelMap.addAttribute("relationId", usersService.getRelationUserId(id));
        modelMap.addAttribute("editUser", usersService.getUserById(id));
        modelMap.addAttribute("action", "/user/userModifyAction");
        modelMap.addAttribute("users", usersService.getUsersList());
        return "/user/userAdd";
    }

    @RequestMapping("/userModifyAction")
    public String userModifyAction(Users users, ModelMap modelMap, int relation, int id, String token, @ModelAttribute("token") String sessionToken) {
        users.setId(id);
        if (token.equals(sessionToken))
            try {
                users.setPassword(PasswordEncoder.encode(users.getUserName(), users.getPassword()));
                usersService.addOrUpdate(users);
                if (relation != 0) {
                    //添加用户关联关系
                    usersService.addUserRelation(users.getId(), relation);
                }
                modelMap.addAttribute("success", "用户修改成功！");
            } catch (Exception e) {
                modelMap.addAttribute("error", "用户修改失败！");
            }
        return "forward:/user/userManager";
    }

    @RequestMapping("/modifyPassword")
    public String modifyPassword(String newPassword, String oldPassword, @ModelAttribute(Constants.USER_INFO_SESSION) Users users, ModelMap modelMap, String token, @ModelAttribute("token") String sessionToken) {
        boolean success = false;
        if (token.equals(sessionToken)) {
            try {
                if (PasswordEncoder.encode(users.getUserName(), oldPassword).equals(users.getPassword())) {
                    users.setPassword(PasswordEncoder.encode(users.getUserName(), newPassword));
                } else {
                    throw new MyException("旧密码不匹配！");
                }
                usersService.addOrUpdate(users);
                modelMap.addAttribute("success", "用户修改成功！");
                success = true;
            } catch (MyException me) {
                modelMap.addAttribute("error", me.getMessage());
                success = false;
            } catch (Exception e) {
                modelMap.addAttribute("error", "用户修改失败！");
                success = false;
            }
        }
        if (!success) {
            return "forward:/user/userManager";
        } else {
            return "forward:/user/logout";
        }
    }


    @RequestMapping("/login")
    public String login(Users user, boolean remember, ModelMap modelMap, HttpServletResponse response) throws Exception {
        Users users = usersService.getUserByName(user.getUserName());
        if (users == null) {
            modelMap.addAttribute("message", "用户不存在");
            return "forward:/login.jsp";
        }
        if (users.getPassword() == null || !PasswordEncoder.encode(user.getUserName(), user.getPassword()).equalsIgnoreCase(users.getPassword())) {
            modelMap.addAttribute("message", "密码错误");
            return "forward:/login.jsp";
        }
        if (remember)
            CookieUtil.addCookie(response, "user", users.getUserName() + "=" + users.getPassword(), 3600);
        modelMap.addAttribute(Constants.USER_INFO_SESSION, users);
        return "redirect:/forward/index/html";
    }

    @RequestMapping("/userManager")
    public String userManager(ModelMap modelMap) throws Exception {
        modelMap.addAttribute("token", StringUtil.uuid());
        modelMap.addAttribute("users", usersService.getUsersList());
        return "/user/userManager";
    }

    @RequestMapping("/stat/{id}")
    public String stat(@PathVariable int id, ModelMap modelMap) throws Exception {
        if (id == 0) {
            Users users = (Users) modelMap.get(Constants.USER_INFO_SESSION);
            id = users.getId();
        }
        modelMap.addAttribute("users", usersService.getUserChild(id));
        return "/user/userStat";
    }

    @RequestMapping("/userDelete/{id}/{token}")
    public String userDelete(ModelMap modelMap, @PathVariable int id, @PathVariable String token, @ModelAttribute("token") String sessionToken) {
        if (token.equals(sessionToken))
            try {
                usersService.deleteUser(id);
                modelMap.addAttribute("success", "用户删除成功！");
            } catch (Exception e) {
                modelMap.addAttribute("error", "用户删除失败！");
            }

        return "forward:/user/userManager";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        request.getSession().removeAttribute(Constants.USER_INFO_SESSION);
        modelMap.remove(Constants.USER_INFO_SESSION);
        CookieUtil.addCookie(response, "user", null, 0);
//        Users users = (Users) request.getSession().getAttribute(Constants.USER_INFO_SESSION);
        return "redirect:/forward/index/html";
    }


    @Autowired
    private IUsersService usersService;
}
